package com.xiaomaoguai.fcp.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.text.SimpleDateFormat;

/**
 * 序列化配置
 *
 * @fileName: SpringMVCConfig.java
 * @author: WeiHui
 * @date: 2018/8/14 19:39
 * @version: v1.0.0
 * @since JDK 1.8
 */
@Configuration
public class WebConfig {

    /**
     * 序列化配置
     */
    private final Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;

    /**
     * inject bean
     *
     * @param jackson2ObjectMapperBuilder bean
     */
    @Autowired
    public WebConfig(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder) {
        this.jackson2ObjectMapperBuilder = jackson2ObjectMapperBuilder;
    }

    /**
     * 序列化配置
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJsonHttpMessageConverter() {
        ObjectMapper objectMapper = jackson2ObjectMapperBuilder.build();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
        // 允许出现特殊字符和转义符
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        // 允许出现单引号
        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));

        return new MappingJackson2HttpMessageConverter(objectMapper);
    }

}
